import { ModalController } from 'ionic-angular/components/modal/modal-controller';
import { ToastController } from 'ionic-angular/components/toast/toast-controller';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';
import { BaseUI } from '../../common/baseui';
import { LoadingController } from 'ionic-angular/components/loading/loading-controller';
import { Storage } from '@ionic/storage';
import { AnswerPage } from '../answer/answer';

/**
 * Generated class for the DetailsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-details',
  templateUrl: 'details.html',
})
export class DetailsPage extends BaseUI {

  id : string
  userId: string
  question: string[]
  answers: string[]
  erroeMessage: any
  isFavourite: boolean
  isMyQuestion: boolean

  constructor(public navCtrl: NavController, 
    public rest: RestProvider,
    public loadingCtrl: LoadingController,
    public toastCtrl: ToastController,
    public storage: Storage,
    public modalCtrl: ModalController,
    public navParams: NavParams) {
      super()
  }

  ionViewDidLoad() {  
   this.id = this.navParams.get('id')
   this.loadingQuestion(this.id)
  }

  loadingQuestion(id) {
    this.storage.get('userId').then(val => {
      console.log(val)
      if(val != null) {
        this.userId = val
        let loading = super.showLoading(this.loadingCtrl, '加载中...')
        this.rest.getQuestionwithUser (id, val)
          .subscribe( q => {
            loading.dismiss()
            this.question = q
            this.answers = q["Answers"]
            this.isFavourite = q["isFavourite"]
            this.isMyQuestion = (q["OwnUserId"] == val)
          },
          error => {
            this.erroeMessage = <any>error
          }
        )
      }
    })
  }

  saveFavourite() {
    let loading = super.showLoading(this.loadingCtrl, '请求中...')
    this.rest.saveFavourite(this.id, this.userId)
      .subscribe(f => {
        if(f["Status"]== 'OK') {
          loading.dismiss()
          super.showToast(this.toastCtrl, this.isFavourite?"取消关注成功":"关注问题成功")
          this.isFavourite = !this.isFavourite
        }
      },
      error => {
        this.erroeMessage = <any>error
      }
    )
  }

  showAnswerPage(){
    let modal = this.modalCtrl.create(AnswerPage, {"id": this.id})
    // 关闭后的回调(父页面的刷新)
    modal.onWillDismiss(() => {
      this.loadingQuestion(this.id)
    })
    modal.present()
  }
}
